package org.twndmv.ejb;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.twndmv.bl.DriverMgmt;
import org.twndmv.blimpl.DriverMgmtImpl;
import org.twndmv.bo.Person;
import org.twndmv.bo.Residence;
import org.twndmv.dao.PersonDAO;
import org.twndmv.dto.DTOUtils;
import org.twndmv.dto.PersonDTO;
import org.twndmv.dto.ResidenceDTO;
import org.twndmv.jpa.PersonDAOImpl;

@Stateless
public class DriverMgmtEJB implements DriverMgmtRemote {

	private static Log log = LogFactory.getLog(DriverMgmtEJB.class);

	@PersistenceContext(unitName = "dmvEntity")
	private EntityManager em;
	
	private DriverMgmt driverManager;
	
	 @PostConstruct
	    public void init() {
	        try {
	            log.info("**** init ****");
	            log.info("em=" + em);
	            PersonDAO personDB = new PersonDAOImpl(em);
	            driverManager = new DriverMgmtImpl(personDB);
	        }
	        catch (Throwable ex) {
	            log.error("error in init", ex);
	            throw new EJBException("error in init" + ex);
	        }
	    }
	
	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public void addDriver(PersonDTO newPerson) {
		Person newPeep = DTOUtils.convertDTOToPerson(newPerson);
		driverManager.addDriver(newPeep);
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public void moveResidence(long personId, ResidenceDTO newResidence) {
		
		Residence newRes = DTOUtils.convertDTOToResidence(newResidence);
		driverManager.moveResidence(personId, newRes);

	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public PersonDTO getDriver(long id) {
		Person newPeep = driverManager.getDriver(id);
		return DTOUtils.convertPersonToDTO(newPeep);
	}

	@Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
	public List<PersonDTO> getDriversByLastName(String name) {
        List<PersonDTO> results = new ArrayList<PersonDTO>();
        for(Person p : driverManager.getDriversByLastName(name)) {
        	PersonDTO person = DTOUtils.convertPersonToDTO(p);
        	results.add(person);
        }
        return results;
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public List<PersonDTO> getAllDrivers() {
		List<PersonDTO> results = new ArrayList<PersonDTO>();
        for(Person p : driverManager.getAllDrivers()) {
        	PersonDTO person = DTOUtils.convertPersonToDTO(p);
        	results.add(person);
        }
        return results;
	}

}
